"use strict";

const Koa = require('koa');
const serve = require('koa-serve');
const convert = require('koa-convert');
const router = require('./router');
const render = require('koa-ejs');
const path = require('path');
const mysql = require('mysql');
const app = new Koa();

//配置数据连接
const pool = mysql.createPool({
  connectionLimit: 10,
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'liuyanban'
});
app.context.dbQuery = (sql) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        return reject(err);
      }
      connection.query(sql, (error, results) => {
        if (error) {
          connection.release();
          return reject(error);
        }
        connection.release();
        return resolve(results);
      });

    });
  });
};

//配置模版引擎
render(app, {
  root: path.join(__dirname, 'view'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true
});
//配置静态文件服务
app.use(convert(serve('static')));

//配置项目路由
router(app);


const PORT = 3000;
app.listen(PORT);
console.log('app is listening port ' + PORT); 
